$(function(){
    let $regBox=$("#registerBox");
    let $loginBox=$("#loginBox");
    let $admin =$("#admin");
    let $logoutBtn=$("#logoutBtn");


    $regBox.find("a.colMint").on("click",function (){
        $regBox.hide();
        $loginBox.show();
    })
    $loginBox.find("a.colMint").on("click",function (){
        $loginBox.hide();
        $regBox.show();
    })
    //注册register
    $("#btnReg").on("click",function (){
        $.ajax({
            type:"post",
            url:"/api/account/register",
            data:{
                username:$regBox.find('[name="username"]').val(),
                password:$regBox.find('[name="password"]').val(),
                passwordAgain:$regBox.find('[name="passwordAgain"]').val(),
            },
            beforeSend:()=>{
                 if($regBox.find('[name="username"]').val()==""){
                    alert("用户名不能为空")
                    return false;
                }else if($regBox.find('[name="password"]').val()==""){
                    alert('密码不能为空')
                    return false;
                }else if($regBox.find('[name="password"]').val()!=$regBox.find('[name="passwordAgain"]').val()) {
                     alert("请确认密码是否一致");
                     return false;
                 }
            },
            dataType:"json",
            success:function (result){
                if(result.msg=="exist"){
                    alert("用户名已存在");
                }
                window.location.href = "/api/login";
            }
        })
    })

    //登入操作
    $("#btnLogin").on("click",function (){
        $.ajax({
            type:"post",
            url:"/api/account/login",
            data:{
                username:$loginBox.find('[name="username"]').val(),
                password:$loginBox.find('[name="password"]').val(),
            },
            dataType:"json",
            success:function (result){
                if(result.code=="200"){
                    alert("可以登入");
                    $admin.show();
                    $loginBox.hide();
                    window.location.href = "/blog";
                    $admin.find('.username').text(result.rspMsg.user);
                }else if(result.code=="201"){
                    alert('该用户不存在')
                }
            }
        })


    })

    $("#logoutBtn").on("click",function (){
        $.ajax({
            type:"get",
            url:"/api/account/logout",
            dataType:"json",
            success:function (result){
                console.log(result.msg);
                if(result.code==="300"){
                    window.location.reload()
                }else if(result.code==="301"){
                    alert(result.rspMsg.msg);
                }
            }
        })
    })

})
